package xyz.scootaloo.oj.leetcode

import org.junit.Test
import xyz.scootaloo.common.TestDsl

/**
 * @author flutterdash@qq.com
 * @since 2021/7/9 21:27
 */
class P566 : TestDsl {

    private fun matrixReshape(mat: Array<IntArray>, r: Int, c: Int): Array<IntArray> {
        val targetCapacity = r * c
        val realCapacity = mat.size * mat[0].size
        if (targetCapacity != realCapacity)
            return mat

        val producer = MatrixIterator(mat)
        val consumer  = MatrixIterator(Array(r) { IntArray(c) })

        while (producer.hasNext()) {
            consumer.set(producer.get())
        }

        return consumer.extract()
    }

    inner class MatrixIterator(private val mat: Array<IntArray>) {
        val row = mat.size
        val column = mat[0].size
        var r = 0
        var c = 0

        fun get(): Int {
            return mat[r][c].also { movePos() }
        }

        fun set(num: Int) {
            mat[r][c] = num
            movePos()
        }

        fun hasNext(): Boolean {
            return r < row
        }

        private fun movePos() {
            c++
            if (c == column) {
                c = 0
                r++
            }
        }

        fun extract() = mat
    }

    @Test
    fun test0() {
        matrixReshape(arrayOf(
            intArrayOf(1, 2),
            intArrayOf(3, 4)
        ), 1, 4).log()
    }

    @Test
    fun test1() {
        matrixReshape(arrayOf(
            intArrayOf(3, 4),
            intArrayOf(5, 6)
        ), 2, 5).log()
    }

}
